package com.myj.jim.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.myj.jim.dao.RoleDao;
import com.myj.jim.domain.Role;
import com.myj.jim.domain.RoleAuthority;
import com.myj.jim.domain.bootstraptable.BootstrapTable;
import com.myj.jim.domain.bootstraptable.BootstrapTableJSON;
import com.myj.jim.service.RoleService;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleDao roleDao;
	
	@Override
	public BootstrapTableJSON<Role> findPage(Map<String,Object> map) {
		List<Role> list = roleDao.findPage(map);
		
		int count = roleDao.count(map);
		
		BootstrapTableJSON<Role> btj = new BootstrapTableJSON<Role>();
		btj.setTotal(count);
		btj.setRows(list);
		
		return btj;
	}

	@Override
	public Role edit(Integer id) {
		return roleDao.selectByPrimaryKey(id);
	}

	@Override
	public Boolean save(Role role, String[] checkedAuthArr) {
		
		boolean success = roleDao.insert(role)!=0;
		
		
		if(checkedAuthArr!=null && checkedAuthArr.length>0){
			Map<String,String> map = new HashMap<String,String>();
			map.put("roleno", role.getRoleno());
			for(String auth : checkedAuthArr){
				if(!"".equals(auth)){
					map.put("authorityno", auth);
					roleDao.saveRoleAuthority(map);
				}
			}
		}
		
		return success;
	}

	@Override
	public Boolean update(Role role, String[] checkedAuthArr) {
		int ret = roleDao.updateByPrimaryKey(role);
		System.out.println(role.getRoleno());
		roleDao.deleteRoleAuthorityByRoleno(role.getRoleno());
		
		if(checkedAuthArr!=null && checkedAuthArr.length>0){
			Map<String,String> map = new HashMap<String,String>();
			map.put("roleno", role.getRoleno());
			for(String auth : checkedAuthArr){
				if(!"".equals(auth)){
					map.put("authorityno", auth);
					roleDao.saveRoleAuthority(map);
				}
			}
		}
		
		return ret!=0;
	}

	@Override
	public Boolean delete(Integer id) {
		
		Role r = roleDao.selectByPrimaryKey(id);
		
		if(r!=null){
			roleDao.deleteRoleAuthorityByRoleno(r.getRoleno());
		}
		
		return roleDao.deleteByPrimaryKey(id)!=0;
	}

	@Override
	public Boolean isExist(String roleno) {
		return roleDao.isExist(roleno)>0;
	}

	@Override
	public List<RoleAuthority> selectRoleAuthorityByRoleno(String roleno) {
		
		return roleDao.selectRoleAuthorityByRoleno(roleno);
	}

	@Override
	public Role getRoleById(Integer id) {
		return roleDao.selectByPrimaryKey(id);
	}

}
